#include "ui_replacement.h"
#include "font/font.h"

#include "lang/lang.h"

#include "util/timer.h"		    // Needs to come in early
#include "util/mmgr.h"		    // Needs to come in early
#include "util/common_macros.h"		// macros
#include "util/log.h"		    // logging

#include <algorithm>
using namespace ui;

static unsigned int	ReplaceSubStr(	std::wstring& s,
									const std::wstring& from,
									const std::wstring& to)
{
	std::string::size_type cnt(std::string::npos);

	if(from != to && !from.empty())
	{
		std::string::size_type pos1(0);
		std::string::size_type pos2(0);
		const std::string::size_type from_len(from.size());
		const std::string::size_type to_len(to.size());
		cnt = 0;

		while((pos1 = s.find(from, pos2)) != std::string::npos)
		{
			s.replace(pos1, from_len, to);
			pos2 = pos1 + to_len;
			++cnt;
		}
	}
	return cnt;
}


UIReplacement&	UIReplacement::Instance()
{
	static UIReplacement Inst;
	return Inst;
}

UIReplacement::UIReplacement()
{

}

UIReplacement::~UIReplacement()
{

}

void UIReplacement::SetReplacement(const std::wstring& BaseSource, const std::wstring& Replace)
{
	std::wstring	Source = std::wstring(L"%") + BaseSource + std::wstring(L"%");
	
	for (unsigned int i=0; i<m_Strings.size(); i++)
	{
		ReplacementStr& Str = m_Strings[i];
		std::wstring TempWstring;
		TempWstring.push_back(Font::FORCE_BOLD);
		for(int i = 0; i < (int)Replace.size(); i++)
			TempWstring.push_back(Replace[i]);
		TempWstring.push_back(Font::FORCE_BOLD);
		if (Str.From == Source)
		{
			Str.To = TempWstring;
			return;
		}
	} 
	ReplacementStr NewStr;
	NewStr.From = Source;
	std::wstring TempWstring;
	TempWstring.push_back(Font::FORCE_BOLD);
	for(int i = 0; i < (int)Replace.size(); i++)
		TempWstring.push_back(Replace[i]);
	TempWstring.push_back(Font::FORCE_BOLD);
	NewStr.To = TempWstring;
	m_Strings.push_back(NewStr);	
}

void UIReplacement::SetReplacement(const std::string& Source, const std::string& Replace)
{
	SetReplacement(	lang::Lang::ConvertAtoW(Source), lang::Lang::ConvertAtoW(Replace));	
}

void UIReplacement::ReplaceAll(std::wstring& SourceStr)
{
	for (unsigned int i=0; i<m_Strings.size(); i++)
	{
		ReplacementStr&	Str = m_Strings[i];
		ReplaceSubStr(SourceStr, Str.From, Str.To);
	}	
}

